package com.social.dao;

import com.social.model.Friend;
import com.social.model.User;
import com.social.util.DBConnection;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 好友数据访问对象
 * 实现好友关系的CRUD操作和推荐算法
 */
public class FriendDAO {
    /**
     * 添加好友请求
     * @param friend 好友关系对象
     * @return 是否成功
     */
    public boolean addFriendRequest(Friend friend) {
        String sql = "INSERT INTO friends (user_id, friend_user_id, status, request_time) VALUES (?, ?, ?, ?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        int affectedRows = 0;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, friend.getUserId());
            pstmt.setInt(2, friend.getFriendUserId());
            pstmt.setInt(3, friend.getStatus());
            pstmt.setTimestamp(4, new Timestamp(friend.getRequestTime().getTime()));

            affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(conn, pstmt, null);
        }
    }

    /**
     * 更新好友请求状态
     * @param friendId 好友关系ID
     * @param status 新状态
     * @return 是否成功
     */
    public boolean updateFriendStatus(int friendId, int status) {
        String sql = "UPDATE friends SET status = ?, process_time = ? WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        int affectedRows = 0;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, status);
            pstmt.setTimestamp(2, new Timestamp(new java.util.Date().getTime()));
            pstmt.setInt(3, friendId);

            affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(conn, pstmt, null);
        }
    }

    /**
     * 删除好友关系
     * @param friendId 好友关系ID
     * @return 是否成功
     */
    public boolean deleteFriend(int friendId) {
        String sql = "DELETE FROM friends WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        int affectedRows = 0;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, friendId);

            affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(conn, pstmt, null);
        }
    }

    /**
     * 获取用户的好友列表
     * @param userId 用户ID
     * @return 好友列表
     */
    public List<Friend> getFriendList(int userId) {
        String sql = "SELECT * FROM friends " +
                "WHERE (user_id = ? OR friend_user_id = ?) " +
                "AND status = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Friend> friendList = new ArrayList<>();

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.setInt(2, userId);
            pstmt.setInt(3, Friend.STATUS_ACCEPTED);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Friend friend = new Friend();
                friend.setId(rs.getInt("id"));
                friend.setUserId(rs.getInt("user_id"));
                friend.setFriendUserId(rs.getInt("friend_user_id"));
                friend.setStatus(rs.getInt("status"));
                friend.setRequestTime(rs.getTimestamp("request_time"));
                friend.setProcessTime(rs.getTimestamp("process_time"));
                friend.setMutualFriendCount(rs.getInt("mutual_friend_count"));

                friendList.add(friend);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return friendList;
    }

    /**
     * 获取用户的好友请求列表
     * @param userId 用户ID
     * @return 好友请求列表
     */
    public List<Friend> getFriendRequests(int userId) {
        String sql = "SELECT * FROM friends WHERE friend_user_id = ? AND status = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Friend> requestList = new ArrayList<>();

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.setInt(2, Friend.STATUS_PENDING);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Friend request = new Friend();
                request.setId(rs.getInt("id"));
                request.setUserId(rs.getInt("user_id"));
                request.setFriendUserId(rs.getInt("friend_user_id"));
                request.setStatus(rs.getInt("status"));
                request.setRequestTime(rs.getTimestamp("request_time"));

                requestList.add(request);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return requestList;
    }

    /**
     * 搜索用户
     * @param userId 当前用户ID
     * @param keyword 搜索关键词
     * @param filter 过滤条件
     * @return 搜索结果列表
     */
    public List<User> searchUsers(int userId, String keyword, String filter) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT u.*, (SELECT COUNT(*) FROM friends f " +
                "WHERE (f.user_id = u.id OR f.friend_user_id = u.id) " +
                "AND f.status = ?) as friend_count ");
        sql.append("FROM users u ");
        sql.append("WHERE u.id != ? ");
        sql.append("AND u.id NOT IN (SELECT friend_user_id FROM friends WHERE user_id = ? AND status = ?) ");
        sql.append("AND u.id NOT IN (SELECT user_id FROM friends WHERE friend_user_id = ? AND status = ?) ");

        // 添加关键词搜索条件
        sql.append("AND (u.nickname LIKE ? OR u.phone LIKE ? OR u.email LIKE ?) ");

        // 添加过滤条件
        if ("friendCountAsc".equals(filter)) {
            sql.append("ORDER BY friend_count ASC ");
        } else if ("friendCountDesc".equals(filter)) {
            sql.append("ORDER BY friend_count DESC ");
        } else if ("active".equals(filter)) {
            sql.append("ORDER BY u.last_active_time DESC ");
        } else {
            sql.append("ORDER BY u.id ASC ");
        }

        sql.append("LIMIT 10"); // 限制结果数量

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql.toString());
            int paramIndex = 1;
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED);    // friend_count子查询条件
            pstmt.setInt(paramIndex++, userId);                    // u.id != ?
            pstmt.setInt(paramIndex++, userId);                    // friend_user_id FROM friends WHERE user_id = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED);    // AND status = ?
            pstmt.setInt(paramIndex++, userId);                    // user_id FROM friends WHERE friend_user_id = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED);    // AND status = ?
            pstmt.setString(paramIndex++, "%" + keyword + "%");      // u.nickname LIKE ?
            pstmt.setString(paramIndex++, "%" + keyword + "%");      // u.phone LIKE ?
            pstmt.setString(paramIndex++, "%" + keyword + "%");      // u.email LIKE ?

            rs = pstmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setNickname(rs.getString("nickname"));
                user.setAvatar(rs.getString("avatar"));
                user.setCity(rs.getString("city"));
                user.setSchool(rs.getString("school"));
                user.setFriendCount(rs.getInt("friend_count"));

                // 获取共同好友数量
                int mutualCount = getMutualFriendCount(userId, user.getId());
                user.setMutualFriendCount(mutualCount);

                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return users;
    }

    /**
     * 获取随机推荐用户
     * @param userId 当前用户ID
     * @param limit 返回数量限制
     * @return 推荐用户列表
     */
    public List<User> getRandomRecommendUsers(int userId, int limit) {
        String sql = "SELECT u.*, (SELECT COUNT(*) FROM friends f " +
                "WHERE (f.user_id = u.id OR f.friend_user_id = u.id) " +
                "AND f.status = ?) as friend_count " +
                "FROM users u " +
                "WHERE u.id != ? " +
                "AND u.id NOT IN (SELECT friend_user_id FROM friends WHERE user_id = ? AND status = ?) " +
                "AND u.id NOT IN (SELECT user_id FROM friends WHERE friend_user_id = ? AND status = ?) " +
                "ORDER BY RAND() " +
                "LIMIT ?";

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> recommendUsers = new ArrayList<>();

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, Friend.STATUS_ACCEPTED);    // friend_count子查询条件
            pstmt.setInt(2, userId);                    // u.id != ?
            pstmt.setInt(3, userId);                    // friend_user_id FROM friends WHERE user_id = ?
            pstmt.setInt(4, Friend.STATUS_ACCEPTED);    // AND status = ?
            pstmt.setInt(5, userId);                    // user_id FROM friends WHERE friend_user_id = ?
            pstmt.setInt(6, Friend.STATUS_ACCEPTED);    // AND status = ?
            pstmt.setInt(7, limit);                     // LIMIT ?

            rs = pstmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setNickname(rs.getString("nickname"));
                user.setAvatar(rs.getString("avatar"));
                user.setCity(rs.getString("city"));
                user.setSchool(rs.getString("school"));
                user.setFriendCount(rs.getInt("friend_count"));

                // 获取共同好友数量
                int mutualCount = getMutualFriendCount(userId, user.getId());
                user.setMutualFriendCount(mutualCount);

                recommendUsers.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return recommendUsers;
    }

    /**
     * 获取共同好友推荐
     * @param userId 当前用户ID
     * @param limit 返回数量限制
     * @return 共同好友推荐列表
     */
    public List<User> getMutualFriendRecommendations(int userId, int limit) {
        String sql = "SELECT u.*, COUNT(mf.id) as mutual_count " +
                "FROM users u " +
                "JOIN ( " +
                "    SELECT f2.friend_user_id " +
                "    FROM friends f1 " +
                "    JOIN friends f2 ON f1.friend_user_id = f2.user_id " +
                "    WHERE f1.user_id = ? " +
                "    AND f1.status = ? " +
                "    AND f2.status = ? " +
                "    AND f2.friend_user_id != ? " +
                "    AND f2.friend_user_id NOT IN (SELECT friend_user_id FROM friends WHERE user_id = ? AND status = ?) " +
                "    AND f2.friend_user_id NOT IN (SELECT user_id FROM friends WHERE friend_user_id = ? AND status = ?) " +
                ") mf ON u.id = mf.friend_user_id " +
                "GROUP BY u.id " +
                "ORDER BY mutual_count DESC, friend_count ASC " +
                "LIMIT ?";

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> recommendUsers = new ArrayList<>();

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            int paramIndex = 1;
            pstmt.setInt(paramIndex++, userId);                // f1.user_id = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED); // f1.status = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED); // f2.status = ?
            pstmt.setInt(paramIndex++, userId);                // f2.friend_user_id != ?
            pstmt.setInt(paramIndex++, userId);                // friend_user_id FROM friends WHERE user_id = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED); // AND status = ?
            pstmt.setInt(paramIndex++, userId);                // user_id FROM friends WHERE friend_user_id = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED); // AND status = ?
            pstmt.setInt(paramIndex++, limit);                  // LIMIT ?

            rs = pstmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setNickname(rs.getString("nickname"));
                user.setAvatar(rs.getString("avatar"));
                user.setCity(rs.getString("city"));
                user.setSchool(rs.getString("school"));
                user.setMutualFriendCount(rs.getInt("mutual_count"));

                // 获取好友数量
                int friendCount = getFriendCount(user.getId());
                user.setFriendCount(friendCount);

                // 获取共同好友ID列表
                List<Integer> mutualFriendIds = getMutualFriendIds(userId, user.getId());
                user.setMutualFriendIds(mutualFriendIds);

                recommendUsers.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return recommendUsers;
    }

    /**
     * 根据条件获取推荐用户
     * @param userId 当前用户ID
     * @param condition 推荐条件
     * @param limit 返回数量限制
     * @return 推荐用户列表
     */
    public List<User> getConditionRecommendations(int userId, String condition, int limit) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT u.*, (SELECT COUNT(*) FROM friends f " +
                "WHERE (f.user_id = u.id OR f.friend_user_id = u.id) " +
                "AND f.status = ?) as friend_count " +
                "FROM users u " +
                "WHERE u.id != ? " +
                "AND u.id NOT IN (SELECT friend_user_id FROM friends WHERE user_id = ? AND status = ?) " +
                "AND u.id NOT IN (SELECT user_id FROM friends WHERE friend_user_id = ? AND status = ?) ");

        // 添加条件过滤
        if ("sameCity".equals(condition)) {
            // 获取当前用户城市
            String city = getUserCity(userId);
            if (city != null && !city.isEmpty()) {
                sql.append("AND u.city = ? ");
            }
        } else if ("sameSchool".equals(condition)) {
            // 获取当前用户学校
            String school = getUserSchool(userId);
            if (school != null && !school.isEmpty()) {
                sql.append("AND u.school = ? ");
            }
        }

        // 添加排序
        if ("friendCountAsc".equals(condition)) {
            sql.append("ORDER BY friend_count ASC ");
        } else if ("friendCountDesc".equals(condition)) {
            sql.append("ORDER BY friend_count DESC ");
        } else if ("sameCity".equals(condition) || "sameSchool".equals(condition)) {
            sql.append("ORDER BY friend_count DESC ");
        } else {
            sql.append("ORDER BY RAND() ");
        }

        sql.append("LIMIT ?");

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> recommendUsers = new ArrayList<>();

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql.toString());
            int paramIndex = 1;
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED);    // friend_count子查询条件
            pstmt.setInt(paramIndex++, userId);                    // u.id != ?
            pstmt.setInt(paramIndex++, userId);                    // friend_user_id FROM friends WHERE user_id = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED);    // AND status = ?
            pstmt.setInt(paramIndex++, userId);                    // user_id FROM friends WHERE friend_user_id = ?
            pstmt.setInt(paramIndex++, Friend.STATUS_ACCEPTED);    // AND status = ?

            if ("sameCity".equals(condition) && getUserCity(userId) != null) {
                pstmt.setString(paramIndex++, getUserCity(userId));
            } else if ("sameSchool".equals(condition) && getUserSchool(userId) != null) {
                pstmt.setString(paramIndex++, getUserSchool(userId));
            }

            pstmt.setInt(paramIndex++, limit);                     // LIMIT ?

            rs = pstmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setNickname(rs.getString("nickname"));
                user.setAvatar(rs.getString("avatar"));
                user.setCity(rs.getString("city"));
                user.setSchool(rs.getString("school"));
                user.setFriendCount(rs.getInt("friend_count"));

                // 获取共同好友数量
                int mutualCount = getMutualFriendCount(userId, user.getId());
                user.setMutualFriendCount(mutualCount);

                // 设置推荐理由
                setRecommendReason(user, condition);

                recommendUsers.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return recommendUsers;
    }

    /**
     * 检查两个用户是否是好友
     * @param userId1 用户1 ID
     * @param userId2 用户2 ID
     * @return 是否是好友
     */
    public boolean isFriend(int userId1, int userId2) {
        String sql = "SELECT COUNT(*) FROM friends " +
                "WHERE ((user_id = ? AND friend_user_id = ?) OR (user_id = ? AND friend_user_id = ?)) " +
                "AND status = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean isFriend = false;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId1);
            pstmt.setInt(2, userId2);
            pstmt.setInt(3, userId2);
            pstmt.setInt(4, userId1);
            pstmt.setInt(5, Friend.STATUS_ACCEPTED);
            rs = pstmt.executeQuery();

            if (rs.next() && rs.getInt(1) > 0) {
                isFriend = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return isFriend;
    }

    /**
     * 检查是否有未处理的好友请求
     * @param userId1 用户1 ID
     * @param userId2 用户2 ID
     * @return 是否有未处理的请求
     */
    public boolean hasPendingRequest(int userId1, int userId2) {
        String sql = "SELECT COUNT(*) FROM friends " +
                "WHERE ((user_id = ? AND friend_user_id = ?) OR (user_id = ? AND friend_user_id = ?)) " +
                "AND status = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean hasPending = false;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId1);
            pstmt.setInt(2, userId2);
            pstmt.setInt(3, userId2);
            pstmt.setInt(4, userId1);
            pstmt.setInt(5, Friend.STATUS_PENDING);
            rs = pstmt.executeQuery();

            if (rs.next() && rs.getInt(1) > 0) {
                hasPending = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return hasPending;
    }

    /**
     * 获取用户的好友数量
     * @param userId 用户ID
     * @return 好友数量
     */
    private int getFriendCount(int userId) {
        String sql = "SELECT COUNT(*) FROM friends " +
                "WHERE (user_id = ? OR friend_user_id = ?) " +
                "AND status = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.setInt(2, userId);
            pstmt.setInt(3, Friend.STATUS_ACCEPTED);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return count;
    }

    /**
     * 获取两个用户的共同好友数量
     * @param userId1 用户1 ID
     * @param userId2 用户2 ID
     * @return 共同好友数量
     */
    private int getMutualFriendCount(int userId1, int userId2) {
        String sql = "SELECT COUNT(*) FROM friends f1 " +
                "JOIN friends f2 ON f1.friend_user_id = f2.friend_user_id " +
                "WHERE f1.user_id = ? " +
                "AND f2.user_id = ? " +
                "AND f1.status = ? " +
                "AND f2.status = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId1);
            pstmt.setInt(2, userId2);
            pstmt.setInt(3, Friend.STATUS_ACCEPTED);
            pstmt.setInt(4, Friend.STATUS_ACCEPTED);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return count;
    }

    /**
     * 获取两个用户的共同好友ID列表
     * @param userId1 用户1 ID
     * @param userId2 用户2 ID
     * @return 共同好友ID列表
     */
    private List<Integer> getMutualFriendIds(int userId1, int userId2) {
        String sql = "SELECT f1.friend_user_id FROM friends f1 " +
                "JOIN friends f2 ON f1.friend_user_id = f2.friend_user_id " +
                "WHERE f1.user_id = ? " +
                "AND f2.user_id = ? " +
                "AND f1.status = ? " +
                "AND f2.status = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Integer> mutualFriendIds = new ArrayList<>();

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId1);
            pstmt.setInt(2, userId2);
            pstmt.setInt(3, Friend.STATUS_ACCEPTED);
            pstmt.setInt(4, Friend.STATUS_ACCEPTED);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                mutualFriendIds.add(rs.getInt("friend_user_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return mutualFriendIds;
    }

    /**
     * 获取用户城市
     * @param userId 用户ID
     * @return 城市名称
     */
    private String getUserCity(int userId) {
        String sql = "SELECT city FROM users WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String city = null;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                city = rs.getString("city");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return city;
    }

    /**
     * 获取用户学校
     * @param userId 用户ID
     * @return 学校名称
     */
    private String getUserSchool(int userId) {
        String sql = "SELECT school FROM users WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String school = null;

        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                school = rs.getString("school");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(conn, pstmt, rs);
        }

        return school;
    }

    /**
     * 设置推荐理由
     * @param user 用户对象
     * @param condition 推荐条件
     */
    private void setRecommendReason(User user, String condition) {
        switch (condition) {
            case "friendCountAsc":
                user.setRecommendReason("好友数较少，容易建立联系");
                break;
            case "friendCountDesc":
                user.setRecommendReason("好友数较多，社交活跃");
                break;
            case "sameCity":
                user.setRecommendReason("与你同城，距离较近");
                break;
            case "sameSchool":
                user.setRecommendReason("与你同校，校友关系");
                break;
            default:
                user.setRecommendReason("系统推荐");
        }
    }

    /**
     * 关闭数据库资源
     * @param conn 数据库连接
     * @param stmt 语句对象
     * @param rs 结果集
     */
    private void closeResources(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}